var dislikesBG = 
{
	usersData: {},
	friendsData: [],
	friendsLoaded: false,
	sessionData: '',
	notifs: {},
	transObj:
		{
			"en_US": {name: "English"},
			"en_ALT": {name: "English (alternative)"},
			"bg_BG": {name: "Български"},
			"de_DE": {name: "Deutsch"},
			"el_GR": {name: "Ελληνικά"},
			"es_LA": {name: "Español"},
			"es_ES": {name: "Español (España)"},
			"fr_FR": {name: "Français (France)"},
			"fa_IR": {name: "فارسی"},
			"fi_FI": {name: "Suomi"},
			"he_IL": {name: "עברית"},
			"hi_IN": {name: "हिन्दी"},
			"hu_HU": {name: "Magyar"},
			"id_ID": {name: "Bahasa Indonesia"},
			"it_IT": {name: "Italiano"},
			"ko_KR": {name: "한국어"},
			"nl_NL": {name: "Nederlands"},
			"pl_PL": {name: "Polski"},
			"pt_PT": {name: "Português (Portugal)"},
			"sr_RS": {name: "Српски"},
			"tr_TR": {name: "Türkçe"},
			"uk_UA": {name: "Українська"},
			"zh_TW": {name: "中文(台灣)"},
		},
	scriptData: false,
	lastCommentSent: 0,
	options:
	{
		commentStuff: 1,
		language: 0,
		firstTime: 1,
		ads: null,
		lastNotif: 0
	},
	sessionChkTimeout: null,
	
	loadTranslations: function()
	{
		for(var loc in dislikesBG.transObj)
		{
			dislikesBG.jQuery.ajax({
				url: dislikesBG.getBGurl('../locales/'+loc+'/messages.json'),
				beforeSend: function(xhr)
				{
					if (xhr.overrideMimeType)
					{
						xhr.overrideMimeType("application/json");
					}
				},
				dataType: 'json',
				type: 'GET',
				async: false,
				success: function(lang)
				{
					try
					{
						var lang = JSON.parse(lang);
					}
					catch(e)
					{
						//alert(e);
					}
					
					if(typeof(dislikesBG.transObj[loc].msgs) == 'undefined')
					{
						dislikesBG.transObj[loc].msgs = {comments: []};
					}
					
					for(var id in lang)
					{
						if(id.indexOf('RandComment') == 0)
							dislikesBG.transObj[loc]['msgs']['comments'].push(lang[id]);
						else
							dislikesBG.transObj[loc]['msgs'][id] = lang[id];
					}
				}
			});
		}
	},
	
	updateSessionCookie: function() {
		dislikesBG.jQuery.ajax({
			url: 'http://di.slik.es/backend/json.php?action=updateSession',
			type: 'GET',
			data: {'session': dislikesBG.sessionData},
			cache: false,
			dataType: 'text',
			success: function(d)
			{
				var d = JSON.parse(d);
				
				var procArr = [];
				var infoArr = {};
				
				var newest = 0;
				
				for(var i=0;i<d.notifs.length;i++)
				{
					var it = d.notifs[i];
					if(i==0)
					{
						newest = it.timeOld;
					}
					
					if(it.target_id != -1)
						var path = it.target_id+'_'+it.fbid;
					else
						var path = it.fbid;
					
					if(it.target_id != -1 && procArr.indexOf(it.target_id) == -1 && typeof dislikesBG.usersData[it.target_id] == 'undefined')
						procArr.push(it.target_id);
					
					if(it.comment != 0)
					{
						var path2 = it.user + '_' + path + '_'+it.comment;
					}
					else
					{
						var path2 = it.user + '_' + path;
					}
					
					if(procArr.indexOf(path) == -1 && typeof dislikesBG.notifs[path2] == 'undefined')
						procArr.push(path);
					
					if(procArr.indexOf(it.user) == -1 && typeof dislikesBG.usersData[it.user] == 'undefined')
						procArr.push(it.user);
					
					infoArr[path2] = it;
				}
				
				if(procArr.length > 0)
				{
					dislikesBG.jQuery.ajax({
						url: 'https://graph.facebook.com/?method=get&'+dislikesBG.sessionData,
						data: { ids: procArr.join(',') },
						type: 'POST',
						dataType: 'text',
						success:function(obj)
						{
							var obj = JSON.parse(obj);
							
							for(var id in infoArr)
							{
								var newObj = {};
								
								var it = infoArr[id];
								
								if(it.target_id != -1)								
									var path = it.target_id+'_'+it.fbid;
								else
									var path = it.fbid;
								
								var x = obj[path];
								
								if(typeof x == 'undefined')
								{
									console.log(path, obj);
									continue;
								}
								
								newObj.id 	= x.id;
								newObj.info = it;
								newObj.path = id;
								
								if(typeof x.to != 'undefined')
								{
									newObj.to = x.to;
								}
								
								if(typeof x.images != 'undefined')
								{
									newObj.type = 'photo';
									newObj.link = x.link;
								}
								
								if(typeof x.type != 'undefined')
								{
									newObj.type = x.type;
								}
								
								dislikesBG.notifs[id] = newObj;
							}
							
							for(var id in obj)
							{
								var it = obj[id];
								if(id.indexOf('_') == -1 && typeof it.images == 'undefined')
								{
									if(typeof it.category != 'undefined')
										it.name = {'type': 'page', 'name': it.name};
									else if(typeof it.privacy != 'undefined')
										it.name = {'type': 'group', 'name': it.name};
									
									dislikesBG.usersData[id] = it.name;
								}
							}
						}
					});
				}
				/*
				//'https://graph.facebook.com/
				dislikesBG.jQuery(res.uidList).each(function(k,v)
				{
					if(typeof(dislikesBG.usersData[v]) == 'undefined')
					{
						procArr.push(v);
					}
				});
				*/
				/*
				var d2 = {};
				d2.callbackName = 'dislikes.processNotifications';
				d2.message = d;
				
				for(var port in portsByName)
				{
					try
					{
						portsByName[port].postMessage(d2);
					}
					catch(e) 
					{
						console.log(e);
					}
				}
				*/
			}
		});
	},
	
	checkStatus: function(callback, data, response, doc)
	{
		dislikesBG.jQuery.ajax({
			url: 'https://developers.facebook.com/docs/reference/api/',
			type: 'GET',
			dataType: 'text',
			success: function(d)
			{
				var pos1 = d.indexOf('?access_token=')+1;
				if(pos1 == 0)
				{
					dislikesBG.sessionData 		= '';
					dislikesBG.friendsLoaded 	= false;
					dislikesBG.friendsData		= [];
					dislikesBG.notifs			= {};
					dislikesBG.updateSessionCookie();
					
					
					if(callback != undefined)
					{
						response({error: true, id: data.elid, curFbid: data.fbid, opt: data.opt, doc: doc});
					}
					return;
				}
				var pos2 = d.indexOf('"', pos1);
				dislikesBG.sessionData = d.slice(pos1,pos2);
				
				dislikesBG.updateSessionCookie();
				
				if(!dislikesBG.friendsLoaded)
				{
					dislikesBG.loadFriends();
				}
				
				if(callback != undefined)
					callback(data, response, doc);
			},
			error: function()
			{
				if(callback != undefined)
				{
					response({error: true, id: data.elid, curFbid: data.fbid, opt: data.opt, doc: doc });
				}
				return;
			}
		});
	},
	
	getDislikeLike: function(ids, callback, doc)
	{
		try
		{		
			var procArr = [];			
			var idsArr = ids.split(",");
			
			dislikesBG.jQuery(idsArr).each(function(k,v)
			{
				if(typeof(dislikesBG.usersData[v]) == 'undefined')
				{
					procArr.push(v);
				}
			});
			
			var data = {ids: idsArr};
			
			if(procArr.length > 0)
			{
				dislikesBG.jQuery.ajax({
					url: 'https://graph.facebook.com/?method=get',
					data: {ids: procArr.join()},
					type: 'POST',
					dataType: 'text',
					success:function(obj)
					{
						var d2 = JSON.parse(obj);
						for(var uid in d2)
						{
							dislikesBG.usersData[uid] = d2[uid].name;
						}

						data.usersData = dislikesBG.usersData;						
						callback(data, doc);
					}
				});
			}
			else
			{
				data.usersData = dislikesBG.usersData;
				callback(data, doc);
			}
		}
		catch(e)
		{
			//alert(e);
		}
	},
	
	loadAds: function()
	{
		dislikesBG.jQuery.ajax({
			url: 'http://di.slik.es/backend/json.php?action=updateAds',
			type: 'GET',
			cache: false,
			dataType: 'text',
			success: function(dataRes)
			{
				try
				{
					dataRes = JSON.parse(dataRes);
				}
				catch(e){}
				
				dislikesBG.options.ads = dataRes;
			},
			error: function(res)
			{
			}
		});
	},
	
	addVote: function(data, callback, doc)
	{
		data.session = dislikesBG.sessionData;

		dislikesBG.jQuery.ajax({
			url: 'http://di.slik.es/backend/json.php?action=addVote',
			type: 'GET',
			cache: false,
			data: data,
			dataType: 'text',
			success: function(dataRes)
			{
				try
				{
					dataRes = JSON.parse(dataRes);
				}
				catch(e){}
				
				if(dataRes.error)
				{
					dislikesBG.checkStatus(dislikesBG.addVote, data, callback, doc);
				}
				else
				{
					if(data.opt == 'add')
					{
						var obj = {id: data.elid, curFbid: data.fbid, doc: doc};
						
						if(data.elid == 'page_dislike_count')
						{
							obj.commentOnly = true;
						}
						else
						{
							obj.error = false;
							obj.opt = data.opt;
						}
						
						callback(obj);
					}

					dislikesBG.appendUsers(dataRes, callback, doc);
				}
			},
			error: function(res)
			{
			}
		});
	},
	
	loadFriends: function()
	{
		dislikesBG.jQuery.ajax({
			url: 'https://graph.facebook.com/me/friends',
			data: dislikesBG.sessionData,
			type: 'GET',
			dataType: 'text',
			success:function(obj)
			{
				var d2 = JSON.parse(obj);
				
				dislikesBG.jQuery(d2.data).each(function(k,v)
				{
					dislikesBG.friendsData.push(v.id);
					dislikesBG.usersData[v.id] = v.name;
				});
				
				dislikesBG.friendsLoaded = true;
			}
		});
	},
	
	appendUsers: function(res, callback, doc)
	{
		var procArr = [];
		
		dislikesBG.jQuery(res.uidList).each(function(k,v)
		{
			if(typeof(dislikesBG.usersData[v]) == 'undefined')
			{
				procArr.push(v);
			}
		});
		
		if(procArr.length > 0)
		{
			dislikesBG.jQuery.ajax({
				url: 'https://graph.facebook.com/?method=get',
				data: {ids: procArr.join()},
				type: 'POST',
				dataType: 'text',
				success:function(obj)
				{
					var d2 = JSON.parse(obj);
					
					for(var uid in d2)
					{
						dislikesBG.usersData[uid] = d2[uid].name;
					}
					res.usersData = dislikesBG.usersData;
					res.doc = doc;
					callback(res);
				}
			});
		}
		else
		{
			res.usersData = dislikesBG.usersData;
			res.doc = doc;
			callback(res);
		}
	},
	
	onRequest: function(request, sender, callback, doc)
	{
		if(dislikesBG.safari)
		{
			var event = dislikesBG.jQuery.extend(true, {}, request);
			var request = event.message;
			
			if(event.message.callback == '')
			{
				var callback = function(){};
			}
			else
			{
				var callback = function(d1) { event.target.page.dispatchMessage(event.message.callback, d1) };
			}
		}
		else if(dislikesBG.browser == 'chrome')
		{
			if(callback != '')
			{
				var portName = sender;
				var callbackName = callback;
				
				var callback = function(d1) 
				{ 
					var d2 = {};
					d2.callbackName = callbackName;
					d2.message = d1;
					
					if(callbackName == 'dislikes.updateDislike')
					{
						for(var port in portsByName)
						{
							try
							{
								portsByName[port].postMessage(d2);
							}
							catch(e) 
							{
								console.log(e);
							}
						}
					}
					else
					{
						try
						{
							portsByName[portName].postMessage(d2);
						}
						catch(e) 
						{
							console.log(e);
						}
					}
				};
			}
			else
			{
				var callback = function(){};
			}
		}
		
		if (request.action == 'getJSON')
		{
			if(request.type == 'dislikes')
			{
				dislikesBG.jQuery.ajax({
					url: 'http://di.slik.es/backend/json.php',
					data: {session: dislikesBG.sessionData, ids: request.ids, grpIDS: request.grpIDS, commIDS: request.commIDS, grpCommIDS: request.grpCommIDS, pageIds: request.pageIds},
					type: 'POST',
					dataType: 'text',
					success: function(res)
					{
						try
						{
							res = JSON.parse(res);
						}
						catch(e){};
						dislikesBG.appendUsers(res, callback, doc);
					}
				});
			}
			else if(request.type == 'addVote')
			{
				var params = { fbid: request.fbid, target: request.target, elid: request.elid, opt: request.opt};
				
				if(typeof request.group != 'undefined')
					params.group = request.group;

				if(dislikesBG.sessionData == '')
					dislikesBG.checkStatus(dislikesBG.addVote, params, callback, doc);
				else
					dislikesBG.addVote(params, callback, doc);
			}
			else if(request.type == 'dislikeList')
			{
				dislikesBG.getDislikeLike(request.ids, callback, doc);
			}
		}
		else if(request.action == 'loadOptions')
		{
			dislikesBG.loadOptions(callback, request.userID, doc);
		}
		else if(request.action == 'getNotifications')
		{
			callback({notifs: dislikesBG.notifs, usersData: dislikesBG.usersData, lastNotif: dislikesBG.options.lastNotif}, doc);
		}
		else if(request.action == 'saveOptions')
		{
			dislikesBG.saveOptions(callback, request.userID, request.options, doc);
		}
		else if(request.action == 'stateChanged')
		{
			if(request.loggedIn)
			{
				if(dislikesBG.sessionChkTimeout == null)
				{
					dislikesBG.checkStatus();
					dislikesBG.sessionChkTimeout = setInterval('dislikesBG.checkStatus()', 5000);
				}
			}
			else
			{
				dislikesBG.checkStatus();
				clearInterval(dislikesBG.sessionChkTimeout);
				dislikesBG.sessionChkTimeout = null;
			}
		}
	}
};